﻿/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

using System.Runtime.InteropServices;
using System.Threading;

namespace Daidalos.Utilities
{

    public class Timer
    {

        private static double hitsPerSecond;
        private long startTime;
        private long endTime;

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("kernel32")]
        public static extern bool QueryPerformanceFrequency(ref long PerformanceFrequency);

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("kernel32")]
        public static extern bool QueryPerformanceCounter(ref long PerformanceCount);

        static Timer()
        {
            // Retrieve the number of hits per second from the performance timer.
            long hits = 0;
            Timer.QueryPerformanceFrequency(ref hits);
            Timer.hitsPerSecond = (double)hits;
        }

        public Timer()
        {
            startTime = 0;
            endTime = 0;
        }

        public void Start()
        {
            Timer.QueryPerformanceCounter(ref startTime);
        }

        public void Stop()
        {
            Timer.QueryPerformanceCounter(ref endTime);
        }

        /// <summary>
        ///     Measures the time span in seconds between
        ///     the start() and stop() call to the timer.
        /// </summary>
        /// <returns>
        ///     Time in seconds between start() and stop().
        /// </returns>
        public double SecondsTimed()
        {
            return (endTime - startTime) / hitsPerSecond;
        }

        /// <summary>
        ///     Measures the time span in seconds since
        ///     the invocation of this message and the
        ///     start of the timer.
        /// </summary>
        /// <returns>
        ///     Time in seconds between start() and now.
        /// </returns>
        public double SecondsElapsed()
        {
            long currentTime = 0;
            Timer.QueryPerformanceCounter(ref currentTime);
            return (currentTime - startTime) / hitsPerSecond;
        }

    }

}
